package com.bnyy.medicalHousekeeper.moudle.message.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.TypedValue;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import androidx.activity.result.ActivityResultLauncher;
import androidx.appcompat.app.AlertDialog;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.blankj.utilcode.util.ScreenUtils;
import com.bnyy.medicalHousekeeper.DialogHelper;
import com.bnyy.medicalHousekeeper.PopupWindowHelper;
import com.bnyy.medicalHousekeeper.R;
import com.bnyy.medicalHousekeeper.base.BaseActivityImpl;
import com.bnyy.medicalHousekeeper.moudle.message.adapter.ContactAdapter;
import com.bnyy.medicalHousekeeper.request.BaseObserverImpl;
import com.bnyy.message.bean.Contact;
import com.bnyy.message.bean.ContactGroup;
import com.bnyy.message.bean.ContactUser;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.function.Consumer;
import java.util.function.Predicate;

import butterknife.BindView;

/**
 * Author : 关炳鹏
 * Description :
 * Date : 2022/11/20
 **/
public class SelectContactActivity extends BaseActivityImpl {

    public static final String RESULT_SELECTED_CONTACT_IDS = "selectedContactIds";
    public static final String RESULT_SELECTED_CONTACTS = "selectedContacts";

    @BindView(R.id.recycler_view)
    RecyclerView recyclerView;
    @BindView(R.id.et_search)
    EditText etSearch;
    @BindView(R.id.iv_clear)
    ImageView ivClear;
    @BindView(R.id.iv_no_data)
    ImageView ivNoData;
    @BindView(R.id.tv_no_data)
    TextView tvNoData;
    @BindView(R.id.ll_no_data)
    LinearLayout llNoData;

    private ContactAdapter adapter;
    //    private int max;
    private boolean singleSelect;
    private ContactAdapter.Callback callback;
    private ArrayList<Contact> selectedContacts = new ArrayList<>();

    public static void show(Context context, String title, ContactAdapter.ConstantItem constantItem, ArrayList<? extends Contact> contacts, ActivityResultLauncher<Intent> launcher) {
        show(context, title, "", true, true, constantItem, contacts, launcher);
    }

    public static void show(Context context, String title, String dialogTips, ArrayList<? extends Contact> contacts, ActivityResultLauncher<Intent> launcher) {
        show(context, title, dialogTips, true, true, null, contacts, launcher);
    }

    /**
     * @param context
     * @param title
     * @param dialogTips   点击确定后提示
     * @param constantItem 常量item
     * @param contacts     联系人
     * @param singleSelect 单选 / 多选
     * @param launcher
     */
    public static void show(
            Context context,
            String title,
            String dialogTips,
            boolean singleSelect,
            boolean search,
            ContactAdapter.ConstantItem constantItem,
            ArrayList<? extends Contact> contacts,
            ActivityResultLauncher<Intent> launcher
    ) {
        if (contacts == null) {
            contacts = new ArrayList<>();
        }
        Intent intent = new Intent(context, SelectContactActivity.class);
        intent.putExtra("title", title);
        intent.putExtra("dialogTips", dialogTips);
        intent.putExtra("singleSelect", singleSelect);
        intent.putExtra("search", search);
        intent.putExtra("constantItem", constantItem);
        intent.putExtra("contacts", contacts);
        launcher.launch(intent);
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_message_select_contact;
    }

    @Override
    public String getTitleStr() {
        return null;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        Intent intent = getIntent();
        ArrayList<Contact> contacts = (ArrayList<Contact>) intent.getSerializableExtra("contacts");

        String title = intent.getStringExtra("title");
        String dialogTips = intent.getStringExtra("dialogTips");
        ContactAdapter.ConstantItem constantItem = (ContactAdapter.ConstantItem) intent.getSerializableExtra("constantItem");
        singleSelect = intent.getBooleanExtra("singleSelect", true);

        setTitleStr(title);

        if (!singleSelect) {
            TextView tvConfirm = new TextView(mContext);
            tvConfirm.setBackgroundResource(R.drawable.selector_button_corner_green_180);
            tvConfirm.setText("确定");
            tvConfirm.setTextSize(TypedValue.COMPLEX_UNIT_SP, 10);
            tvConfirm.setTextColor(Color.WHITE);
            tvConfirm.setPadding(15, 5, 15, 5);
//            tvConfirm.setEnabled(false);
            tvConfirm.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (selectedContacts.size() > 0) {
                        if (!TextUtils.isEmpty(dialogTips)) {
                            DialogHelper.showNormalDialog(mContext, dialogTips,
                                    new DialogHelper.Callback() {
                                        @Override
                                        public void onRightClick(AlertDialog alertDialog) {
                                            super.onRightClick(alertDialog);
                                            setResult();
                                        }
                                    });
                        } else {
                            setResult();
                        }
                    } else {
                        finish();
                    }
                }
            });
            setOptions(tvConfirm);
        }

        etSearch.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_DOWN) {
                    Editable text = etSearch.getText();
                    if (!TextUtils.isEmpty(text)) {
                        String keyword = text.toString();
                        ArrayList<Contact> targetContacts = new ArrayList<>();

                        contacts.forEach(new Consumer<Contact>() {
                            @Override
                            public void accept(Contact contact) {
                                String name = "";
                                if (contact instanceof ContactUser) {
                                    ContactUser contactUser = (ContactUser) contact;
                                    name = contactUser.getUsername();
                                } else if (contact instanceof ContactGroup) {
                                    ContactGroup contactGroup = (ContactGroup) contact;
                                    name = contactGroup.getGroup_name();
                                }

                                if (name.contains(keyword)) {
                                    targetContacts.add(contact);
                                }
                            }
                        });

                        if (targetContacts.size() > 0) {
                            adapter.refresh(targetContacts);
                        } else {
                            Toast.makeText(mContext, "无匹配的联系人", Toast.LENGTH_SHORT).show();
                        }

                        return true;
                    }
                }
                return false;
            }
        });
        etSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                ivClear.setVisibility(TextUtils.isEmpty(s) ? View.GONE : View.VISIBLE);
            }
        });

        ivClear.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                etSearch.setText("");
                adapter.refresh(contacts, constantItem);
            }
        });

        callback = new ContactAdapter.CallbackImpl() {

            @Override
            public void onConstantItemClick(ContactAdapter.Constant constant) {
                super.onConstantItemClick(constant);
                switch (constant) {
                    case FAMILY:
                        requestManager.request(requestManager.mMessageRetrofitService.getFamilyList(),
                                new BaseObserverImpl<ArrayList<ContactUser>>() {
                                    @Override
                                    public void onSuccess(ArrayList<ContactUser> contactUsers) {
                                        super.onSuccess(contactUsers);
                                        if (contactUsers.size() > 0) {
                                            if (singleSelect) {
                                                showSingleSelectConstantPopWin(mContext, contactUsers, constant, callback);
                                            } else {
                                                HashSet<Integer> set = new HashSet<>();
                                                for (Contact contact : selectedContacts) {
                                                    set.add(contact.getId());
                                                }
                                                showMultipleSelectConstantPopWin(mContext, contactUsers, constant, set, callback);
                                            }
                                        } else {
                                            Toast.makeText(mContext, "暂无数据", Toast.LENGTH_SHORT).show();
                                        }
                                    }
                                });
                        break;
                    case GROUP:
                        requestManager.request(requestManager.mMessageRetrofitService.getGroupList(),
                                new BaseObserverImpl<ArrayList<ContactGroup>>(mContext) {
                                    @Override
                                    public void onSuccess(ArrayList<ContactGroup> contactGroups) {
                                        super.onSuccess(contactGroups);
                                        if (contactGroups.size() > 0) {
                                            if (singleSelect) {
                                                showSingleSelectConstantPopWin(mContext, contactGroups, constant, callback);
                                            } else {
                                                HashSet<Integer> set = new HashSet<>();
                                                for (Contact contact : selectedContacts) {
                                                    set.add(contact.getId());
                                                }
                                                showMultipleSelectConstantPopWin(mContext, contactGroups, constant, set, callback);
                                            }
                                        } else {
                                            Toast.makeText(mContext, "暂无数据", Toast.LENGTH_SHORT).show();
                                        }
                                    }
                                });
                        break;
                }
            }

            @Override
            public void onItemClick(Contact contact, int position) {
                super.onItemClick(contact, position);
                if (singleSelect) {
                    selectedContacts.add(contact);
                    setResult();
                }
            }

            @Override
            public void onCheck(Contact contact, boolean checked, int position) {
                super.onCheck(contact, checked, position);
                if (checked) {
                    selectedContacts.add(contact);
                } else {
                    selectedContacts.removeIf(new Predicate<Contact>() {
                        @Override
                        public boolean test(Contact c) {
                            return c.getId() == contact.getId();
                        }
                    });
                }
            }
        };
        adapter = new ContactAdapter(mContext, singleSelect, callback);
        recyclerView.setLayoutManager(new LinearLayoutManager(mContext));
        recyclerView.setAdapter(adapter);
        if (constantItem == null && contacts.size() == 0) {
            llNoData.setVisibility(View.VISIBLE);
        } else {
            adapter.refresh(contacts, constantItem);
        }
    }

    private void setResult() {
        Intent intent = new Intent();
        HashSet<Integer> selectedContactIds = new HashSet<>();
        for (Contact contact : selectedContacts) {
            selectedContactIds.add(contact.getId());
        }
        intent.putExtra(RESULT_SELECTED_CONTACT_IDS, selectedContactIds);
        intent.putExtra(RESULT_SELECTED_CONTACTS, selectedContacts);
        setResult(RESULT_OK, intent);
        finish();
    }

    public static void showSingleSelectConstantPopWin(Activity activity, ArrayList<? extends Contact> contacts,
                                                      ContactAdapter.Constant constant, ContactAdapter.Callback callback) {
        show(activity, contacts, true, callback, new Consumer<ContactAdapter>() {
            @Override
            public void accept(ContactAdapter contactAdapter) {
                contactAdapter.refresh(contacts, new ContactAdapter.ConstantItem(constant.getName()));
            }
        });
    }

    public static void showMultipleSelectConstantPopWin(Activity activity, ArrayList<? extends Contact> contacts, ContactAdapter.Constant constant,
                                                        HashSet<Integer> selectedIds, ContactAdapter.Callback callback) {
        show(activity, contacts, false, callback, new Consumer<ContactAdapter>() {
            @Override
            public void accept(ContactAdapter contactAdapter) {
                contactAdapter.refresh(contacts, new ContactAdapter.ConstantItem(constant.getName()), selectedIds);
            }
        });
    }

    public static void show(Activity activity, ArrayList<? extends Contact> contacts, boolean singleSelect,
                            ContactAdapter.Callback callback, Consumer<ContactAdapter> consumer) {

        LayoutInflater inflater = LayoutInflater.from(activity);
        View root = inflater.inflate(R.layout.pop_win_select_contact, null);

        PopupWindow popupWindow = PopupWindowHelper.getInstance(activity).show(root, ScreenUtils.getScreenWidth(), ScreenUtils.getScreenHeight() / 5 * 4);
        popupWindow.setOutsideTouchable(false);

        root.findViewById(R.id.tv_confirm).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
            }
        });
        EditText etSearch = root.findViewById(R.id.et_search);
        ImageView ivClear = root.findViewById(R.id.iv_clear);

        ContactAdapter contactAdapter = new ContactAdapter(activity, singleSelect, new ContactAdapter.CallbackImpl() {

            @Override
            public void onConstantItemClick(ContactAdapter.Constant constant) {
                super.onConstantItemClick(constant);
                callback.onConstantItemClick(constant);
            }

            @Override
            public void onCheck(Contact contact, boolean checked, int position) {
                super.onCheck(contact, checked, position);
                callback.onCheck(contact, checked, position);
            }

            @Override
            public void onItemClick(Contact contact, int position) {
                if (singleSelect) {
                    popupWindow.dismiss();
                }
                callback.onItemClick(contact, position);
            }
        });

        RecyclerView recyclerView = root.findViewById(R.id.recycler_view);
        recyclerView.setLayoutManager(new LinearLayoutManager(activity));
        recyclerView.setAdapter(contactAdapter);

        consumer.accept(contactAdapter);

        etSearch.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_DOWN) {
                    Editable text = etSearch.getText();
                    if (!TextUtils.isEmpty(text)) {
                        String keyword = text.toString();
                        ArrayList<Contact> targetContacts = new ArrayList<>();

                        contacts.forEach(new Consumer<Contact>() {
                            @Override
                            public void accept(Contact contact) {
                                String name = "";
                                if (contact instanceof ContactUser) {
                                    ContactUser contactUser = (ContactUser) contact;
                                    name = contactUser.getUsername();
                                } else if (contact instanceof ContactGroup) {
                                    ContactGroup contactGroup = (ContactGroup) contact;
                                    name = contactGroup.getGroup_name();
                                }

                                if (name.contains(keyword)) {
                                    targetContacts.add(contact);
                                }
                            }
                        });

                        if (targetContacts.size() > 0) {
                            contactAdapter.refresh(targetContacts);
                        } else {
                            Toast.makeText(activity, "无匹配的联系人", Toast.LENGTH_SHORT).show();
                        }

                        return true;
                    }
                }
                return false;
            }
        });
        etSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                ivClear.setVisibility(TextUtils.isEmpty(s) ? View.GONE : View.VISIBLE);
            }
        });

        ivClear.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                etSearch.setText("");
                consumer.accept(contactAdapter);
            }
        });
    }
}

































